﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using System.Reflection;

namespace Web.Resource
{
    /// <summary>
    /// 资源文件扩展名后台验证特性   
    /// </summary>
    [AttributeUsageAttribute(AttributeTargets.Method)]
    public class ResExtensionAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 允许的扩展名
        /// </summary>
        private string[] extArray;

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="allowExts">允许的扩展名</param>
        /// <example>.txt;.doc</example>
        public ResExtensionAttribute(string allowExts)
        {
            this.extArray = allowExts.Matches(@"\.\w+").Select(item => item.ToLower()).ToArray();
        }

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="formatEnumType">文件格式枚举类型</param>
        public ResExtensionAttribute(Type formatEnumType)
        {
            this.extArray = formatEnumType.GetFields(BindingFlags.Static | BindingFlags.Public).Select(item => "." + item.Name.ToLower()).ToArray();
        }

        /// <summary>
        /// 资源扩展名权限验证
        /// </summary>
        /// <param name="filterContext">权限上下文</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            int count = filterContext.HttpContext.Request.Files.Count;
            for (int i = 0; i < count; i++)
            {
                HttpPostedFileBase file = filterContext.HttpContext.Request.Files[i];
                if (file != null)
                {
                    string ext = Path.GetExtension(file.FileName).ToLower();
                    if (this.extArray.Contains(ext) == false)
                    {
                        // 告诉前台401
                        filterContext.Result = new HttpUnauthorizedResult();
                        break;
                    }
                }
            }
        }
    }
}